<template>
  <!-- 组织架构 -->
  <div class="dashboard-container">
    <div class="app-container">

      <el-card class="tree-card">
        <!-- 用了一个行列布局 -->
        <!-- 公司头部 -->
        <treeTools :tree-node="company" :is-root="true" @addDepartment="addDepartment" />
        <hr>
        <!-- 树形结构 -->
        <el-tree :data="departs" default-expand-all :expand-on-click-node="false">
          <template #default="{data}">
            <treeTools :showdialog="showdialog" :tree-node="data" :is-root="false" @delDepartment="getDepartment" @addDepartment="addDepartment" @editDepartment="editDepartment" />
          </template>
        </el-tree>
      </el-card>
    </div>
    <!-- 添加按钮 -->
    <addDept ref="editDept" :showdialog.sync="showdialog" :node-data="treeNode" @addDepartment="getDepartment" />
  </div>
</template>

<script>
import treeTools from './components/tree-tools.vue'
import { getDepartment } from '@/api/department'
import addDept from './components/add-dept.vue'
import { listToTreeData } from '@/utils/index'
export default {
  components: {
    treeTools,
    addDept
  },

  data() {
    return {
      company: { label: '江苏传智播客教育科技股份有限公司', manager: '负责人', id: '' },
      departs: [],
      showdialog: false,
      treeNode: {}
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async  getDepartment() {
      const { depts } = await getDepartment()
      console.log(depts)
      this.departs = listToTreeData(depts, '')
    },
    // 第一种  递归
    // listToTreeData(list, topPid) {
    //   const res = []
    //   // 根据传入topid，查找列表中符合pid的集合
    //   list.forEach(item => {
    //     if (item.pid === topPid) {
    //       // 每找到一个单前级别的部门
    //       // 就以这个部门的id作为下一次搜索的pid
    //       item.children = this.listToTreeData(list, item.id)
    //       res.push(item)
    //     }
    //   })
    //   // console.log(res)
    //   return res
    // },
    // 第二种
    // listToTreeData(list, topPid) {
    //   list.forEach(item => {
    //     if (item.pid !== topPid) {
    //       // 如果pid不为空，就必须是子部门
    //       // 找出自己的父部门送上门
    //       const parent = list.find(el => el.id === item.pid)
    //       if (parent) {
    //         parent.children = parent.children || []
    //         parent.children.push(item)
    //       }
    //     }
    //   })
    //   // 多余的删掉
    //   return list.filter(item => item.pid === topPid)
    // },
    // 点击添加按钮
    addDepartment(treeNode) {
      this.showdialog = true
      this.treeNode = treeNode
    },
    // 点击编辑按钮
    editDepartment(treeNode) {
      this.showdialog = true
      this.treeNode = treeNode
      this.$refs.editDept.getDepartmentDetails(treeNode.id)
    }
  }
}
</script>

<style scoped>
.tree-card {
  padding: 30px  140px;
  font-size:14px;

}
.pointer{
  cursor: pointer;
}
</style>
